package com.tools.hry.xls;

import com.tools.hry.xls.analysis.AnalysisResult;
import com.tools.hry.xls.analysis.ICallbackFunction;
import com.tools.hry.xls.analysis.util.Entity_FieldsUtils;
import com.tools.hry.xls.analysis.util.ReadExcelUtils;
import com.tools.hry.xls.exception.ExcelParseException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 解析Excel to JAVABEAN工具类
 * Created by 峥桂 on 2017/9/5.
 */
public class AnalysisXlsTool {


    /**
     * 读取Excel内容
     * @param inputStream
     * @param classType
     * @param rowStart
     * @param iCallbackFunction
     * @param <T>
     * @return
     * @throws ExcelParseException
     * @throws InvalidFormatException
     * @throws IOException
     */
    public static <T> List<T> readInputStreamAndToEntity(InputStream inputStream, Class<T> classType,
                                                         int sheetPage, int rowStart,
                                                         ICallbackFunction iCallbackFunction) throws Exception {
       return readInputStreamAndToEntity(inputStream, classType,sheetPage,rowStart,true,iCallbackFunction);
    }

    /**
    * 读取Excel内容
    * @param inputStream
    * @param classType
    * @param rowStart
    * @param iCallbackFunction
    * @param <T>
    * @return
     * @throws ExcelParseException
    * @throws InvalidFormatException
    * @throws IOException
    */
    public static <T> List<T> readInputStreamAndToEntity(InputStream inputStream, Class<T> classType,
                                                          int sheetPage, int rowStart,boolean ignoreNullRow,
                                                          ICallbackFunction iCallbackFunction) throws Exception {
        AnalysisResult result=new AnalysisResult();
        Entity_FieldsUtils entity_fieldsUtils=new Entity_FieldsUtils();//转换实体bean
        ReadExcelUtils readExcelUtils;//读取excel文件Bean
        List<T> listT=null;
        try {
            //解析Excel
            readExcelUtils =new ReadExcelUtils();
            readExcelUtils.readExcel(inputStream,sheetPage,rowStart,ignoreNullRow);
            //处理解析文件后的数据封装成bean
            iCallbackFunction.before(result);
            listT=entity_fieldsUtils.toEntitys(classType,readExcelUtils.getHeaders(),readExcelUtils.getDatas());
            result.setErrorLogBeans(entity_fieldsUtils.getErrorLogBeans());
            if(iCallbackFunction!=null) {
                iCallbackFunction.after(result);
            }

        } catch (Exception e) {
            result.setException(e);
            result.setErrorLogBeans(entity_fieldsUtils.getErrorLogBeans());
            if(iCallbackFunction!=null) {
                iCallbackFunction.onFailure(result);
            }
            return null;
        }
        iCallbackFunction.onSuccess(result,listT);
        return  listT;
    }


}
